package cn.edu.swu.auth;

import com.mysql.cj.Session;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginServlet extends HttpServlet{

    private Map<String, User> Users = new HashMap<>();

    //处理web.xml中初始化的信息，分成每个user最后放入集合Users中
    public void init(ServletConfig config){
        String userString = config.getInitParameter("users");
        String[] userPass = userString.split(";");
        for(String item : userPass){
            String[] userAndPass = item.split("@");
            User user = new User(userAndPass[0], userAndPass[1]);
            this.Users.put(user.getName(),user);
        }
        System.out.println("update!");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request,response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("user");
        String password = request.getParameter("password");
        String code = request.getParameter("code");

/*
        Users是解析后的用户信息；
        而这里的name和password是获得用户输入的信息
*/

        HttpSession session = request.getSession(true);
        String authcode = (String) session.getAttribute(AuthCodeServlet.AUTH_CODE);
        if(authcode == null || !authcode.equals(code)){
            response.sendRedirect("./admin.html");
            return;
        }

        User user = this.Users.get(name);
        if(user != null){
            if(user.getPassword().equals(password)){
                response.addCookie(new Cookie("P-user", name));
                session = request.getSession(true);
                session.setAttribute(AuthFilter.LOGIN_TAG,AuthFilter.LOGIN_TAG_SUCCESS);
                response.sendRedirect("./picture/list");
                return;
            }
        }
        response.sendRedirect("./admin.html");
    }
}

        //修改过的代码如下：
//        if(user != null && user.equals("admin")){
//            if(password != null && password.equals("fy123")){
//                response.sendRedirect("./main.html");
//                return;
//            }
//        }
